import {BaseInterceptor, InterceptorConfig} from './base';

declare const unsafeWindow: Window & typeof globalThis;

export class XHRInterceptor extends BaseInterceptor {
    private readonly originalXHR: typeof XMLHttpRequest;

    constructor(config: InterceptorConfig) {
        super(config);
        this.originalXHR = unsafeWindow.XMLHttpRequest;
    }

    init(): void {
        const self = this;
        console.log('✈️ XHRInterceptor 初始化')

        unsafeWindow.XMLHttpRequest = function () {
            const xhr = new self.originalXHR();
            const open = xhr.open;
            const TIMEOUT = -1;

            // 覆盖 timeout 属性
            Object.defineProperty(xhr, 'timeout', {
                get: function () {
                    return TIMEOUT;
                },
                set: function (timeout) {
                    console.log("⌛️ 原始请求超时时间: ", timeout, "ms", "已被覆盖，永不超时");
                },
                configurable: true
            });

            xhr.open = function (method: string, url: string, async: boolean = true, user?: string | null, password?: string | null) {
                const fullUrl = new URL(url, window.location.href).href;

                console.group('XMLHttpRequest 请求拦截');
                console.log('😊 原始请求:', fullUrl);

                // 处理 URL 重定向和参数
                const {finalUrl, matchedConfig, isRedirected} = self.processUrl(fullUrl);

                // 处理代理
                const proxiedUrl = self.handleProxy(finalUrl, isRedirected);

                console.log('🔄 最终请求:', proxiedUrl);

                // 调用原始的 open 方法
                open.call(this, method, proxiedUrl, async, user, password);

                try {
                    // 添加全局请求头
                    const enabledGlobalHeaders = self.getEnabledHeaders(self.config.globalHeaders);
                    Object.entries(enabledGlobalHeaders).forEach(([key, value]) => {
                        xhr.setRequestHeader(key, value);
                    });
                    console.log('🌍 添加全局请求头:', enabledGlobalHeaders);

                    // 添加特定配置的请求头
                    if (matchedConfig?.headers) {
                        const enabledConfigHeaders = self.getEnabledHeaders(matchedConfig.headers);
                        Object.entries(enabledConfigHeaders).forEach(([key, value]) => {
                            xhr.setRequestHeader(key, value);
                        });
                        console.log('✌️ 添加配置请求头:', enabledConfigHeaders);
                    }
                } catch (error) {
                    console.error('❌ 添加请求头时出错:', error);
                }

                // 修改 send 方法
                const originalSend = xhr.send;
                xhr.send = function (body?: Document | XMLHttpRequestBodyInit | null) {
                    try {
                        console.log('📝 原始请求参数:', {
                            method: method,
                            url: proxiedUrl,
                            body: body || '{}'
                        });

                        // 处理请求体
                        const processedBody = self.processRequestBody(body, matchedConfig);
                        originalSend.call(this, processedBody);
                    } catch (error) {
                        console.error('发送请求时出错:', error);
                        throw error;
                    } finally {
                        console.groupEnd();
                    }
                };
            };

            return xhr;
        } as any;

        console.log('✅ XHRInterceptor 初始化完成')
    }

    destroy(): void {
        if (this.originalXHR) {
            unsafeWindow.XMLHttpRequest = this.originalXHR;
            console.log('🛑 XHRInterceptor 已销毁')
        }
    }
} 